package com.qf.utils;

import com.qf.pojo.Usermanager;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 2019/11/19 0019
 * Author->DT
 * qmxc
 * 行到水穷处 坐看云起时
 * 模块：登录过滤器
 */
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.强转
        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse resp= (HttpServletResponse) response;

        //2.获取请求路径
        String uri = req.getRequestURI();

        //3.校验
        if (uri.endsWith("login.jsp")||uri.endsWith("login")||uri.endsWith("css")||uri.contains("img")){
            //放行必要资源
            chain.doFilter(req, resp);
        }else {
            //4.、得到Session中的user对象
            Usermanager  user= (Usermanager) req.getSession().getAttribute("user");

            //5、校验
            if (user==null){
                //未登录
                response.setContentType("text/html;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script>alert('请先登录');location.href='login.jsp'</script>");
            }else {
                //登录，放行
                chain.doFilter(request, response);
            }
        }


    }

    @Override
    public void destroy() {

    }
}
